package AdminService

import (
	"context"
	"database/sql"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

func Person(ctx context.Context, req *BaseReq.I) *response.JsonResponse {
	cacheAdminId := gconv.String(req.AdminId)
	cacheDuration := g.Cfg().GetDuration("site.AdminCacheTimeout") * time.Second
	obj := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).WherePri(
		"id",
		req.AdminId,
	)
	// 过滤字段
	if len(req.InfoIgnoreProperty) > 0 {
		obj.Fields(obj.GetFieldsExStr(req.InfoIgnoreProperty))
	}
	res, err := obj.Cache(cacheDuration, "adminCache:model:"+cacheAdminId).One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	if res.IsEmpty() {
		return response.FailByRequestMessage(nil, "获取信息失败")
	}
	result := res.Map()
	// 删除敏感信息
	delete(result, "password")
	delete(result, "password_salt")
	// 取部门
	resCon, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_department").Where(
		"id",
		result["dept_id"],
	).Fields("name").Cache(cacheDuration,
		"adminCache:depaName:"+cacheAdminId).Value()
	result["departmentName"] = resCon.String()
	// 取角色
	roleIds, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "admin_role").Where(
		"admin_id",
		result["id"],
	).Fields("role_id").Cache(cacheDuration,
		"adminCache:roleIdList:"+cacheAdminId).Array()
	result["roleIdList"] = gconv.SliceInt(roleIds)
	// 给图片加上前缀
	/*if strings.Index(gconv.String(result["avatar"]), "http") < 0 {
		// 不存在http
		result["avatar"] = g.Cfg().GetString("upload.PhotoPreFix") + gconv.String(result["avatar"])
	}*/
	return response.SuccessByRequestMessageData(nil, "获取成功",
		result)
}
